package com.example.a2306_shop.detail

import androidx.lifecycle.viewModelScope
import com.example.lib_base.entity.AddCartEntity
import com.example.lib_base.entity.CommentEntity
import com.example.lib_base.entity.CreateOrderEntity
import com.example.lib_base.entity.DetailEntity
import com.example.lib_base.entity.Res
import com.example.lib_base.mvvm.BaseViewModel
import com.example.lib_base.param.CreateOrder
import com.example.lib_base.utils.SingleLiveData
import kotlinx.coroutines.launch

class DetailViewModel:BaseViewModel() {

    val detailSuccess = SingleLiveData<Res<DetailEntity>>()
    val detailFail = SingleLiveData<String>()
    fun detail(id:Int,type:String){
        viewModelScope.launch {
            try {
                detailSuccess.postValue(apiService.detail(id, type))
            } catch (e: Exception) {
                detailFail.postValue(e.message.toString())
            }
        }
    }
    val addSuccess = SingleLiveData<Res<AddCartEntity>>()
    val addFail = SingleLiveData<String>()
    fun addCart(cartNum:Int,productAttrUnique:String,productId:Int){
        viewModelScope.launch {

            try {
                val map = mutableMapOf<String,Any>()
                map["cartNum"] = cartNum //商品数量
                map["productAttrUnique"] = productAttrUnique //商品属性id  value中的id
                map["productId"] = productId//商品id
                addSuccess.postValue(apiService.addCart(mapToBody(map)))
            } catch (e: Exception) {
                addFail.postValue(e.message.toString())
            }
        }
    }
    //获取评论
    val commentSuccess = SingleLiveData<Res<CommentEntity>>()
    val commentFail = SingleLiveData<String>()
    fun comment(id:Int,limit:Int,page:Int,type:String){
        viewModelScope.launch {
            try {
                commentSuccess.postValue(apiService.comment(id, limit, page, type))
            } catch (e: Exception) {
                commentFail.postValue(e.message.toString())
            }
        }
    }

    //创建订单
    val createSuccess = SingleLiveData<Res<CreateOrderEntity>>()
    val createFail = SingleLiveData<String>()
    fun orderCreate(createOrder: CreateOrder){
        viewModelScope.launch {
            try {
                createSuccess.postValue(apiService.orderCreate(createOrder))
            } catch (e: Exception) {
                createFail.postValue(e.message.toString())
            }
        }
    }
}